package top.yokey.shopai.main.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.view.View;
import android.view.WindowManager;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.yokey.shopai.R;
import top.yokey.shopai.main.viewmodel.MainLoadVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ImageHelp;
import top.yokey.shopai.zcom.help.SharedHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.other.CountDown;
import top.yokey.shopai.zsdk.ShopAISdk;
import top.yokey.shopai.zsdk.callback.DownCallBack;

@Route(path = ARoutePath.MAIN_LOAD)
public class MainLoadActivity extends BaseActivity {

    private AppCompatImageView mainImageView = null;

    private String advert = "";
    private boolean click = false;
    private boolean deprecated = false;
    private MainLoadVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_main_load);
        mainImageView = findViewById(R.id.mainImageView);

    }

    @Override
    public void initData() {

        vm = getVM(MainLoadVM.class);
        observeKeyborad(R.id.mainLinearLayout);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        vm.getAndroidConfig();

    }

    @Override
    public void initEvent() {

        mainImageView.setOnClickListener(view -> click = true);

    }

    @Override
    public void initObserve() {

        vm.getAndroidConfigLiveData().observe(this, bean -> {
            advert = bean.getAndroidAdvertUrl();
            ImageHelp.get().display(bean.getAndroidAdvertLink(), mainImageView);
            View.OnClickListener listener = view -> downloadApk(bean.getAndroidApkUrl());
            if (!bean.getAndroidVersionControl().contains(App.get().getVersion() + ":1")) {
                deprecated = true;
                DialogHelp.get().query(get(), R.string.doYouWantToUpdate, R.string.versionDeprecatedPleaseUpdate, view -> onReturn(false), listener);
                return;
            }
            if (!bean.getAndroidAppVersion().equals(App.get().getVersion())) {
                deprecated = false;
                DialogHelp.get().query(get(), R.string.doYouWantToUpdate, bean.getAndroidUpdateContent(), view -> getMemberData(), listener);
                return;
            }
            getMemberData();
        });

        vm.getMemberLiveData().observe(this, bean -> {
            App.get().setMemberBean(bean);
            startMain();
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                DialogHelp.get().query(get(), R.string.doYouWantToRetry, bean.getReason(), view -> onReturn(false), view -> vm.getAndroidConfig());
                return;
            }
            if (bean.getReason().equals("请登录")) {
                SharedHelp.get().putString(Constant.SHARED_MEMBER_KEY, "");
                ToastHelp.get().show(bean.getReason());
                ShopAISdk.get().setKey("");
                App.get().startMemberLogin();
                onReturn(false);
                return;
            }
            ToastHelp.get().show(bean.getReason());
        });

    }

    @Override
    public void onResume() {

        super.onResume();
        List<String> list = new ArrayList<>();
        for (String permissions : getPermissions()) {
            if (ContextCompat.checkSelfPermission(get(), permissions) != PackageManager.PERMISSION_GRANTED) {
                list.add(permissions);
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(get(), permissions)) {
                    list.add(permissions);
                }
            }
        }
        if (list.size() > 0) {
            ActivityCompat.requestPermissions(get(), list.toArray(new String[0]), 0);
            return;
        }
        vm.getAndroidConfig();

    }

    //自定义方法

    private void startMain() {

        new CountDown(Constant.TIME_COUNT, Constant.TIME_TICK) {
            @Override
            public void onFinish() {
                super.onFinish();
                App.get().startMain(click ? advert : "");
                onReturn(false);
            }
        }.start();

    }

    private void getMemberData() {

        if (!App.get().isMemberLogin()) {
            startMain();
            return;
        }
        vm.getMember();

    }

    private String[] getPermissions() {

        return new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };

    }

    private void downloadApk(String apkUrl) {

        ProgressDialog progressDialog = new ProgressDialog(get());
        progressDialog.setCancelable(false);
        ShopAISdk.get().down(apkUrl, new DownCallBack() {
            @Override
            public void onStart() {
                ToastHelp.get().show(R.string.startDownload);
            }

            @Override
            public void onProgress(float progress) {
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage(getString(R.string.downloadIng));
                progressDialog.show();
                progressDialog.setMax(100);
                progressDialog.setProgress((int) (progress * 100));
                progressDialog.setProgressNumberFormat(" ");
            }

            @Override
            public void onSuccess(File file) {
                App.get().startInstallApk(get(), getPackageName(), file);
                progressDialog.dismiss();
                onReturn(false);
            }

            @Override
            public void onFailure(String reason) {
                progressDialog.dismiss();
                DialogHelp.get().query(get(), R.string.downloadFailure, reason, view -> {
                    if (deprecated) {
                        onReturn(false);
                    } else {
                        getMemberData();
                    }
                }, view -> downloadApk(apkUrl));
            }
        });

    }

}
